package gweb

import (
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"gorm.io/gorm"
	"net/http"
	"reflect"
	"time"
)

const (
	JsonSuccessCode   = 0
	JsonFailCode      = 1
	JsonAuthFailCode  = 1000
	JsonPanicFailCode = 9000
)

// BaseModel 基础model
type BaseModel struct {
	ID        int            `json:"id" gorm:"primarykey"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"deleted_at"`
}

// BaseListFormParam 统一列表请求参数结构体
type BaseListFormParam struct {
	Page     int `form:"page" binding:"required,gte=1"`
	PageSize int `form:"page_size" binding:"required,lte=50,gte=1"`
}

// JsonResult 统一返回格式
type JsonResult struct {
	Code int64       `json:"code" example:"0"` // 错误码，0：表示成功；其它错误码：表示有错误
	Msg  string      `json:"msg" example:"ok"` // 错误码描述信息
	Data interface{} `json:"data"`             // 业务数据
}

// Json 统一返回
func Json(ctx *gin.Context, code int64, msg string, data interface{}) {
	json := JsonResult{
		Code: code,
		Msg:  msg,
		Data: data,
	}
	ctx.Set("json", json)
	ctx.JSON(http.StatusOK, json)
}

// GetBindArg 获取access_token绑定数据
func GetBindArg(ctx *gin.Context, path string) gjson.Result {
	v, exist := ctx.Get("bindArg")
	if !exist {
		return gjson.Result{}
	}
	if reflect.String.String() != reflect.TypeOf(v).String() {
		return gjson.Result{}
	}
	return gjson.Get(v.(string), path)
}

